﻿using JYH.Data;
using JYH.DataAccess;
using JYH.Business;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Windows.Forms;




namespace JYH.ERP.Smart
{

    public class MaterialInfo
    {

        private readonly System.Timers.Timer  _timer;


        /// <summary>
        /// 物料信息同步对象
        /// </summary>
        /// <param name="intervalHours">同步频率 以分钟为单位</param>
        public MaterialInfo( double intervalHours)
        {
           

            // 设置定时器（以小时为单位）
            _timer = new System.Timers.Timer(intervalHours * 60 * 1000);
            _timer.Elapsed += CleanOldFiles;
            _timer.AutoReset = true;
            _timer.Enabled = true;

            // 首次启动时立即执行一次
            CleanOldFiles(null, null);
        }

        private async void CleanOldFiles(object sender, ElapsedEventArgs e)
        {
            try
            {
               await Task.Run(() => SyncData());
            }
            catch (Exception ex)
            {
                
            }
        }

        public void Start() => _timer.Start();
        public void Stop() => _timer.Stop();


        /// <summary>
        /// 数据同步
        /// </summary>
        /// <returns></returns>
        private async Task SyncData()
        {
            string Msg=string.Empty;
            try
            {
               bool res= SmartERP.SyncMaterialInfo(DateTime.Now.ToString("yyyy-MM-dd"),"",out Msg);
                if (!res) 
                {
                    string Path = Application.StartupPath + @"\\Log\\";
                    if (!Directory.Exists(Path))
                    {
                        Directory.CreateDirectory(Path);
                    }
                    Path +="\\"+ DateTime.Now.ToString("yyyyMMddHHmmss")+ ".txt";
                    File.WriteAllText(Path, Msg);
                }
            }
            catch (Exception ex)
            {

                string Path = Application.StartupPath + @"\\Log\\";
                if (!Directory.Exists(Path))
                {
                    Directory.CreateDirectory(Path);
                }
                Path += "\\" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt";
                File.WriteAllText(Path, ex.ToString());
            }
        }
    }


}
